import pysoem
import time
import csv
from datetime import datetime

master = pysoem.Master()
master.open('eth1')
master.config_dc()

if master.config_init() > 0:
    master.config_map()
    
    for slave in master.slaves:
        print(f"slave name is {slave.name}")
        print(f"slave state is {slave.state}")
        print(f"slave id is {slave.id}")

    master.state_check(pysoem.SAFEOP_STATE, 50000)
    master.state_check(pysoem.OP_STATE, 50000)
    master.write_state()
    master.in_op = True

    with open('output.csv', 'w', newline='') as csvfile:
        csvwriter = csv.writer(csvfile)
        # 写入 CSV 文件的表头
        csvwriter.writerow(['Timestamp'] + [f'NET_{i}' for i in range(1, 17)])

        try:
            while True:
                master.send_processdata()
                master.receive_processdata(2000)

                # 读取 TxPDO 数据
                slave = master.slaves[0]
                
                
                # 假设 NET_1 到 NET_16 每个数据占用 4 字节 (32 位)
                data_offset = 0
                data_length = 4
                
                # 获取当前时间戳
                timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
                
                row_data = [timestamp]


                for i in range(1, 17):
                    data_end = data_offset + data_length
                    value = int.from_bytes(slave.input[data_offset:data_end], byteorder='little', signed=True)
                    print(f"NET_{i}: {value}")
                    row_data.append(value)
                    data_offset += data_length
                
                csvwriter.writerow(row_data)

                # 添加一个小延迟以避免 CPU 占用过高
                time.sleep(0.01)

        except KeyboardInterrupt:
            print("KeyboardInterrupt")
        # print(slave.input)

        finally:
            master.state = pysoem.INIT_STATE
            master.write_state()
            master.close()